//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package com.imagemanager.util;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Rect;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory.Options;
import android.net.Uri;
import android.util.Log;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLConnection;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.params.HttpClientParams;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.SingleClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;

public class UriTexture extends Texture {
    public static final int MAX_RESOLUTION = 1024;
    private static final String TAG = "UriTexture";
    protected String mUri;
    protected long mCacheId;
    private static final int MAX_RESOLUTION_A = 1024;
    private static final int MAX_RESOLUTION_B = 1024;
    public static final String URI_CACHE = CacheService.getCachePath("hires-image-cache");
    private static final String USER_AGENT = "Cooliris-ImageDownload";
    private static final int CONNECTION_TIMEOUT = 20000;
    public static final HttpParams HTTP_PARAMS;
    public static final SchemeRegistry SCHEME_REGISTRY;
    private SingleClientConnManager mConnectionManager;

    static {
        HttpParams params = new BasicHttpParams();
        HttpConnectionParams.setStaleCheckingEnabled(params, false);
        HttpConnectionParams.setConnectionTimeout(params, 20000);
        HttpConnectionParams.setSoTimeout(params, 20000);
        HttpClientParams.setRedirecting(params, true);
        HttpProtocolParams.setUserAgent(params, "Cooliris-ImageDownload");
        HTTP_PARAMS = params;
        SCHEME_REGISTRY = new SchemeRegistry();
        SCHEME_REGISTRY.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        File uri_cache = new File(URI_CACHE);
        uri_cache.mkdirs();
    }

    public UriTexture(String imageUri) {
        this.mUri = imageUri;
    }

    public void setCacheId(long id) {
        this.mCacheId = id;
    }

    public static final Bitmap createFromUri(Context context, String uri, int maxResolutionX, int maxResolutionY, long cacheId, ClientConnectionManager connectionManager) throws IOException, URISyntaxException, OutOfMemoryError {
        final Options options = new Options();
        options.inScaled = false;
        options.inPreferredConfig = Config.RGB_565;
        options.inDither = false;
        long crc64 = 0L;
        Bitmap bitmap = null;
        if(uri.startsWith("content")) {
            crc64 = cacheId;
        } else {
            crc64 = Utils.Crc64Long(uri);
        }

        bitmap = createFromCache(crc64, maxResolutionX);
        if(bitmap != null) {
            return bitmap;
        } else {
            boolean local = uri.startsWith("content") || uri.startsWith("file://");
            int sampleSize = 1;
            if(uri.startsWith("content")) {
                options.inJustDecodeBounds = true;
                InputStream is = context.getContentResolver().openInputStream(Uri.parse(uri));
                if(is == null){
                    return null;
                }
                BufferedInputStream bufferedInput = new BufferedInputStream(is, 16384);
                bufferedInput.mark(2147483647);
                BitmapFactory.decodeStream(bufferedInput, (Rect)null, options);
                int width = options.outWidth;
                int height = options.outHeight;
                float maxResX = (float)maxResolutionY;
                if(width > height) {
                    maxResX = (float)maxResolutionX;
                }

                float maxResY = (float)(maxResX == (float)maxResolutionX?maxResolutionY:maxResolutionX);
                int ratioX = (int)Math.ceil((double)((float)width / maxResX));
                int ratioY = (int)Math.ceil((double)((float)height / maxResY));
                int ratio = Math.max(ratioX, ratioY);
                ratio = Shared.nextPowerOf2(ratio);
                sampleSize = ratio;
                options.inDither = false;
                options.inJustDecodeBounds = false;
                options.inSampleSize = ratio;
                Thread timeoutThread = new Thread("BitmapTimeoutThread") {
                    public void run() {
                        try {
                            Thread.sleep(6000L);
                            options.requestCancelDecode();
                        } catch (InterruptedException var2) {
                            ;
                        }

                    }
                };
                timeoutThread.start();
                bufferedInput.close();
                bufferedInput = new BufferedInputStream(context.getContentResolver().openInputStream(Uri.parse(uri)), 16384);
                bitmap = BitmapFactory.decodeStream(bufferedInput, (Rect)null, options);
                bufferedInput.close();
            } else {
                try {
                    InputStream contentInput = null;
                    if(connectionManager == null) {
                        URL url = (new URI(uri)).toURL();
                        URLConnection conn = url.openConnection();
                        conn.connect();
                        contentInput = conn.getInputStream();
                    } else {
                        DefaultHttpClient mHttpClient = new DefaultHttpClient(connectionManager, HTTP_PARAMS);
                        HttpUriRequest request = new HttpGet(uri);
                        HttpResponse httpResponse = null;

                        try {
                            httpResponse = mHttpClient.execute(request);
                        } catch (IOException var22) {
                            Log.w("UriTexture", "Request failed: " + request.getURI());
                            throw var22;
                        }

                        HttpEntity entity = httpResponse.getEntity();
                        if(entity != null) {
                            contentInput = entity.getContent();
                        }
                    }

                    if(contentInput != null) {
                        BufferedInputStream bufferedInput = new BufferedInputStream(contentInput, 4096);
                        bitmap = BitmapFactory.decodeStream(bufferedInput, (Rect)null, options);
                        bufferedInput.close();
                    }
                } catch (Exception var23) {
                    Log.e("UriTexture", "Error loading image from uri " + uri);
                }
            }

            if(sampleSize > 1 || !local) {
                writeToCache(crc64, bitmap, maxResolutionX);
            }

            return bitmap;
        }
    }

    public static final String createFilePathFromCrc64(long crc64, int maxResolution) {
        return URI_CACHE + crc64 + "_" + maxResolution + ".cache";
    }

    public static boolean isCached(long crc64, int maxResolution) {
        String file = null;
        Options options = new Options();
        options.inScaled = false;
        options.inPreferredConfig = Config.RGB_565;
        options.inDither = false;
        if(crc64 != 0L) {
            file = createFilePathFromCrc64(crc64, maxResolution);

            try {
                new FileInputStream(file);
                return true;
            } catch (Exception var6) {
                return false;
            }
        } else {
            return false;
        }
    }

    public static Bitmap createFromCache(long crc64, int maxResolution) {
        try {
            String file = null;
            Bitmap bitmap = null;
            Options options = new Options();
            options.inScaled = false;
            options.inPreferredConfig = Config.RGB_565;
            options.inDither = false;
            if(crc64 != 0L) {
                file = createFilePathFromCrc64(crc64, maxResolution);
                bitmap = BitmapFactory.decodeFile(file, options);
            }

            return bitmap;
        } catch (Exception var6) {
            return null;
        }
    }

    public static String writeHttpDataInDirectory(Context context, String uri, String path) {
        long crc64 = Utils.Crc64Long(uri);
        if(!isCached(crc64, 1024)) {
            Bitmap bitmap;
            try {
                bitmap = createFromUri(context, uri, 1024, 1024, crc64, (ClientConnectionManager)null);
            } catch (OutOfMemoryError var10) {
                return null;
            } catch (IOException var11) {
                return null;
            } catch (URISyntaxException var12) {
                return null;
            }

            bitmap.recycle();
        }

        String fileString = createFilePathFromCrc64(crc64, 1024);

        try {
            File file = new File(fileString);
            if(file.exists()) {
                String newPath = path + (path.endsWith("/")?"":"/") + crc64 + ".jpg";
                File newFile = new File(newPath);
                Utils.Copy(file, newFile);
                return newPath;
            } else {
                return null;
            }
        } catch (Exception var9) {
            return null;
        }
    }

    public static void writeToCache(long crc64, Bitmap bitmap, int maxResolution) {
        String file = createFilePathFromCrc64(crc64, maxResolution);
        if(bitmap != null && file != null && crc64 != 0L) {
            try {
                File fileC = new File(file);
                fileC.createNewFile();
                FileOutputStream fos = new FileOutputStream(fileC);
                BufferedOutputStream bos = new BufferedOutputStream(fos, 16384);
                bitmap.compress(CompressFormat.JPEG, 80, bos);
                bos.flush();
                bos.close();
                fos.close();
            } catch (Exception var8) {
                ;
            }
        }

    }

    public static void invalidateCache(long crc64, int maxResolution) {
        String file = createFilePathFromCrc64(crc64, maxResolution);
        if(file != null && crc64 != 0L) {
            try {
                File fileC = new File(file);
                fileC.delete();
            } catch (Exception var5) {
                ;
            }
        }

    }

    public void finalize() {
        if(this.mConnectionManager != null) {
            this.mConnectionManager.shutdown();
        }

    }
}
